package main

import (
	"fmt"
	"math"
	"path/filepath"

	"demserver/src/elevation"
)

func main() {
	// Use the actual GeoTIFF file
	filename := "./demdata/scdjy.tif"

	// Get absolute path to the file
	absPath, err := filepath.Abs(filename)
	if err != nil {
		fmt.Printf("Failed to get absolute path: %v\n", err)
		return
	}

	fmt.Printf("Loading GeoTIFF file: %s\n", absPath)
	geoTiff, err := elevation.LoadGeoTIFF(absPath)
	if err != nil {
		fmt.Printf("Failed to load GeoTIFF: %v\n", err)
		return
	}
	fmt.Println("GeoTIFF loaded successfully")

	// Test with the provided high precision coordinates
	// 103.55147461467699,31.03021050140226正确的是837.6951116196124
	lat := 31.03021050140226
	lon := 103.55147461467699
	expected := 837.6951116196124

	x, y, err := geoTiff.LatLonToPixel(lat, lon)
	if err != nil {
		fmt.Printf("Failed to convert coordinates (%.14f, %.14f): %v\n", lat, lon, err)
		return
	}

	fmt.Printf("Input coordinates:\n")
	fmt.Printf("  Lat: %.14f\n", lat)
	fmt.Printf("  Lon: %.14f\n", lon)
	fmt.Printf("Pixel coordinates:\n")
	fmt.Printf("  X: %.14f\n", x)
	fmt.Printf("  Y: %.14f\n", y)

	// Get elevation value
	elevationVal, err := geoTiff.GetElevation(x, y)
	if err != nil {
		fmt.Printf("Failed to get elevation at (%.14f, %.14f): %v\n", x, y, err)
		return
	}

	fmt.Printf("Expected elevation: %.14f\n", expected)
	fmt.Printf("Actual elevation: %.14f\n", elevationVal)
	fmt.Printf("Difference: %.14f\n", elevationVal-expected)

	// Test with integer pixel coordinates for comparison
	xInt := int(x)
	yInt := int(y)

	fmt.Printf("\nInteger pixel coordinates:\n")
	fmt.Printf("  X: %d\n", xInt)
	fmt.Printf("  Y: %d\n", yInt)

	elevationInt, err := geoTiff.GetElevation(float64(xInt), float64(yInt))
	if err != nil {
		fmt.Printf("Failed to get elevation at (%d, %d): %v\n", xInt, yInt, err)
		return
	}

	fmt.Printf("Elevation at integer coordinates: %.14f\n", elevationInt)
	fmt.Printf("Difference from expected: %.14f\n", elevationInt-expected)

	// Test with floor and ceil values
	fmt.Printf("\nFloor and ceil pixel coordinates:\n")
	xFloor := math.Floor(x)
	yFloor := math.Floor(y)
	xCeil := math.Ceil(x)
	yCeil := math.Ceil(y)

	fmt.Printf("  Floor X: %.0f, Floor Y: %.0f\n", xFloor, yFloor)
	fmt.Printf("  Ceil X: %.0f, Ceil Y: %.0f\n", xCeil, yCeil)

	// Check all four corner pixels
	corners := [][2]float64{
		{xFloor, yFloor},
		{xFloor, yCeil},
		{xCeil, yFloor},
		{xCeil, yCeil},
	}

	fmt.Printf("\nCorner pixel values:\n")
	for i, corner := range corners {
		elev, err := geoTiff.GetElevation(corner[0], corner[1])
		if err != nil {
			fmt.Printf("  Corner %d (%.0f, %.0f): Error - %v\n", i, corner[0], corner[1], err)
		} else {
			fmt.Printf("  Corner %d (%.0f, %.0f): %.14f\n", i, corner[0], corner[1], elev)
		}
	}
}
